package com.example.server.service.admin.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.server.common.constant.Result;
import com.example.server.entity.Config;
import com.example.server.mapper.ConfigMapper;
import com.example.server.service.admin.ConfigService;
import com.example.server.vo.ConfigVO;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 系统配置表(Config)表服务实现类
 *
 * @author china.fuyao@outlook.com
 * @since 2020-03-25 18:29:30
 */
@Service("configService")
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService {
    /**
     * 新增配置
     *
     * @param configVO
     * @param customerId
     * @return
     */
    @Override
    public Result addConfig(ConfigVO configVO, Integer customerId) {
        Config sc = new Config();
        BeanUtil.copyProperties(configVO, sc);
        sc.setAddUid(customerId);
        sc.setUpdateUid(customerId);
        LocalDateTime date = LocalDateTime.now();
        sc.setAddTime(date);
        sc.setUpdateTime(date);
        boolean save = this.save(sc);
        if (save) {
            return Result.OK("新增成功");
        }
        return Result.Error("新增失败");
    }

    /**
     * 修改配置
     *
     * @param configVO
     * @param customerId
     * @return
     */
    @Override
    public Result updateConfig(ConfigVO configVO, Integer customerId) {
        if (null != configVO) {
            Config one = getOne(new QueryWrapper<Config>().eq("config_key", configVO.getConfigKey()));
            if (null == one) {
                return Result.Error("配置不存在");
            }
            Config config = new Config();
            BeanUtil.copyProperties(configVO, config);
            config.setUpdateUid(customerId);
            config.setUpdateTime(LocalDateTime.now());
            boolean update = update(config, new QueryWrapper<Config>().eq("config_key", configVO.getConfigKey()));
            if (update) {
                return Result.OK("更新成功");
            }
            return Result.Error("更新失败");
        }
        return Result.Error("参数异常");
    }

    /**
     * 通过config_key获取value
     *
     * @param key
     * @return
     */
    @Override
    public String getValueByKey(String key) {
        Config config = getOne(new QueryWrapper<Config>().eq("config_key", key));
        if (null == config) {
            return null;
        }
        return config.getConfigValue();
    }
}